// pages/login/login.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    account: '', // 账号
    password: '', // 密码
    phoneNum: '', // 手机号码
    telephone: '', // 加密手机号码
    code: '', // 验证码
    status: 0, // 登录按钮状态 0灰色 1蓝色 2正在登录 3维护
    error: false,
    flag: 0, // 0密码登录 1手机登录
    num: 60,
    timer: null,
    isNum: true,
    message: '请填写正确的验证码',
    passFlag: true
  },

  // 手机验证登录
  checkCode() {
    var code = this.data.code,
      phoneNum = this.data.phoneNum;
    if (code == '') {
      wx.showToast({
        title: '请输入验证码',
        iocn: 'none'
      })
      this.setData({
        error: true
      })
      return
    }

    wx.showLoading({
      title: '验证中',
    })
    var that = this,
      url = app.globalData.url + 'member/codeLogin',
      error = '',
      message = '';

    app.wxRequest(url, {
      telNum: phoneNum,
      code: code,
    }, res => {
      if (res.flag) {
        wx.hideLoading()
        console.log(res);
        if (res.data.flag == "fail") {
          error = true;
          if (res.msg) {
            message = res.data.msg;
          } else {
            message = res.data.member;
          }
        } else if (res.data.flag = "success") {
          app.globalData.member = res.data.member
          app.globalData.memberId = res.data.member.memberId
          app.globalData.departmentId = res.data.member.departmentId
          wx.setStorageSync('isLogin', true)
          wx.setStorageSync('member_id', res.data.member.memberId)
          wx.setStorageSync('member', JSON.stringify(res.data.member))
          wx.setStorageSync('department_id', res.data.member.departmentId)
          wx.showToast({
            title: '登录成功',
            icon: 'none'
          })
          wx.switchTab({
            url: '/pages/index/index',
          })
        }
        that.setData({
          error,
          message
        })

      } else {
        wx.showToast({
          title: '验证失败，请重试',
          icon: 'none'
        })
        wx.hideLoading()
      }
    })
  },

  // 重新获取验证码
  getAgain() {
    if (this.data.isNum == false) {
      this.getCode();
      this.setData({
        isNum: true
      })
    }
  },
  back() {
    this.setData({
      flag: 1
    })
  },
  // 获取验证码
  getCode() {
    var phoneNum = this.data.phoneNum;
    if (phoneNum == '') {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '获取中',
    })

    var that = this,
      url = app.globalData.url + 'member/getCode',
      telephone = '',
      error = '',
      status = '',
      flag = '';

    app.wxRequest(url, {
      telNum: phoneNum
    }, res => {
      console.log(res);
      if (res.flag) {
        // 提取字符串某部分: 起始索引（开始位置），终止索引（结束位置）
        telephone = phoneNum.substring(0, 3) + '****' + phoneNum.substring(7);
        var reg_tel =
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
        if (phoneNum == '') {
          error = true;
          return false;
        } else if (!reg_tel.test(phoneNum)) {
          error = true;
          return false;
        } else {
          status = 0;
        }
        flag = 2;
        that.numData();
        that.setData({
          telephone,
          error,
          status,
          flag
        })
        wx.hideLoading()
      } else if (res.message = '失败') {
        wx.showToast({
          title: '获取失败，请稍后再试',
          icon: 'none'
        })
        wx.hideLoading()
      } else {
        wx.showToast({
          title: '获取失败，请稍后再试',
          icon: 'none'
        })
        wx.hideLoading()
      }
    })
  },
  // 倒计时
  numData() {
    var timer = '',
      num = this.data.num,
      isNum = '',
      that = this;
    timer = setInterval(() => {
      num = num - 1;
      that.setData({
        num
      })
      if (num == 0) {
        clearInterval(timer);
        num = 60;
        isNum = false;
        that.setData({
          num,
          isNum
        })
      }
    }, 1000)
  },
  telInpBlur(e) {
    var tel = e.detail.value
    if (!this.validator(tel)) {
      wx.showToast({
        title: '手机号格式有误',
        icon: 'none'
      })
      return
    }
  },
  // 验证手机号 和座机号
  validator: function (val) {
    return /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(val) || /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/.test(val);
  },

  // 登录
  loginOk() {
    var account = this.data.account,
      password = this.data.password;
    if (account == '') {
      wx.showToast({
        title: '请输入账号',
        icon: 'none'
      })
      return
    }
    if (password == '') {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '登录中',
    })
    console.log(account);
    console.log(password);
    var url = app.globalData.url + "member/accountLogin",
      status = '',
      error = '',
      that = this;
    app.wxRequest(
      url, {
        account,
        password
      },
      res => {
        that.setData({
          status: 2
        })
        if (res.flag) {
          wx.hideLoading()
          console.log(res);
          if (res.data.flag == 'fail') {
            status = 0
            error = true
            wx.showToast({
              title: res.data.member,
              icon: 'none'
            })
          } else {
            app.globalData.member = res.data.member
            app.globalData.memberId = res.data.member.memberId
            app.globalData.departmentId = res.data.member.departmentId
            wx.setStorageSync('isLogin', true)
            wx.setStorageSync('member_id', res.data.member.memberId)
            wx.setStorageSync('member', JSON.stringify(res.data.member))
            wx.setStorageSync('department_id', res.data.member.departmentId)
            wx.showToast({
              title: '登录成功',
              icon: 'none'
            })
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
          that.setData({
            status,
            error
          })
        } else {
          wx.showToast({
            title: '登录失败,请重试',
            icon: 'none'
          })
        }
      }
    )
  },

  passHandle() {
    var flag = !this.data.passFlag
    this.setData({
      passFlag: flag
    })
  },

  inputHandle(e) {
    var name = e.currentTarget.dataset.name,
      val = e.detail.value;
    this.setData({
      [name]: val
    })

    var flag = this.data.flag,
      account = this.data.account,
      password = this.data.password,
      status = this.data.status,
      phoneNum = this.data.phoneNum,
      code = this.data.code;

    if (flag == 0) {
      if (account != '' && password != '') {
        status = 1;
      } else if (account == '' || password == '') {
        status = 0;
      }
    } else if (flag == 1) {
      if (phoneNum != '') {
        status = 1;
      } else if (phoneNum == '') {
        status = 0;
      }
    } else if (flag = 2) {
      if (code != '') {
        status = 1;
      } else if (code == '') {
        status = 0;
      }
    }

    this.setData({
      status
    })
  },

  // 切换登陆方式
  checkLogin(e) {
    var flag = e.currentTarget.dataset.flag
    // 手机登录
    if (flag == 'tel') {
      this.setData({
        flag: 1,
        error: false,
        status: 0,
        password: '',
        account: ''
      })
    } else if (flag == 'code') {
      this.setData({
        flag: 0,
        error: false,
        status: 0,
        phoneNum: ''
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})